class MPWorker(object):
    def __init__(self, logdir, args=[], logfile_tag=None, errfile_tag=None, donefile_tag=None):
        self.logdir = logdir
        self.args = args
                
        self.logfile = None
        self.errlog  = None

        self.logfile_tag  = logfile_tag
        self.errfile_tag  = errfile_tag
        self.donefile_tag = donefile_tag


    def __call__(self):
        if self.logfile_tag:
            self.logpath = os.path.join(self.logdir, '{0}.{1}.out'.format(os.getpid(), self.logfile_tag))
        else:
            self.logpath = os.path.join(self.logdir, '{0}.out'.format(os.getpid()))

        if self.errfile_tag:
            self.errpath = os.path.join(self.logdir, '{0}.{1}.err'.format(os.getpid(), self.errfile_tag))
        else:
            self.errpath = os.path.join(self.logdir, '{0}.err'.format(os.getpid()))
        
            
        try:
            self.work(*self.args)
        except Exception, e:
            self.error(traceback.format_exc())
            self.cleanup()
            return

        self.completed()

    def cleanup(self):
        if self.logfile:
            self.logfile.close()
        if self.errlog:
            self.errlog.close()            

    def work(self, *args):
        pass
    
    def completed(self):
        if self.donefile_tag is not None:            
            open(os.path.join(self.logdir, '{0}.{1}.done'.format(os.getpid(), self.donefile_tag)), 'w').close()
        else:
            open(os.path.join(self.logdir, '{0}.done'.format(os.getpid())), 'w').close()

    def log(self, *args):
        self.logfile = open(self.logpath, 'a+')        
        self.logfile.write(" ".join(map(str, args)) + '\n')
        self.logfile.flush()

    def error(self, *args):
        self.errlog = open(self.errpath, 'a+')
        self.errlog.write(" ".join(map(str, args)) + '\n')
        self.errlog.close()

